package com.ncepu.clubmanagement.aop;

import com.ncepu.clubmanagement.exception.AccessDeniedException;
import com.ncepu.clubmanagement.pojo.inter.PermissionLevel;
import com.ncepu.clubmanagement.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class PermissionAspect {

    @Autowired
    private JwtUtils jwtUtil;

    @Autowired
    private HttpServletRequest request;


    @Around("@annotation(com.ncepu.clubmanagement.anno.BackPermission)")
    public Object aroundBack(ProceedingJoinPoint joinPoint) throws Throwable {
        // 方法执行前：获取权限
        // 通过请求的jwt获取用户权限
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer permission = (Integer) claims.get("permission");
        // 方法执行前：判断权限
        if (PermissionLevel.isBackground(permission)) {    // 后台级别权限
            return joinPoint.proceed();  // 通过
        }
        throw new AccessDeniedException();   // 不通过，抛出权限异常

    }
    @Around("@annotation(com.ncepu.clubmanagement.anno.CommitteePermission)")
    public Object aroundCommittee(ProceedingJoinPoint joinPoint) throws Throwable {
        // 方法执行前：获取权限
        // 通过请求的jwt获取用户权限
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer permission = (Integer) claims.get("permission");
        // 方法执行前：判断权限
        if (PermissionLevel.isCommittee(permission)) {    // 团委级别权限
            return joinPoint.proceed();  // 通过
        }
        throw new AccessDeniedException();   // 不通过，抛出权限异常

    }

}
